import { http, toast } from 'uview-plus'
import lodash from 'lodash'
import { getToken, setToken } from '@/util/auth'

export default function (vm) {
    let isRefreshing = false
    let failedQueue = []
    let isGoLogin = false

    /**
     * 处理token刷新的逻辑
     * @param {Object} response 响应对象
     * @returns {Promise} 返回处理结果的Promise
     */
    const handleTokenRefresh = async (config) => {
        // 如果已经在刷新中，将请求添加到失败队列
        if (!isRefreshing) {
            isRefreshing = true
            try {
                // 调用刷新token的API
                const res = await http.post('/test/api/refresh-token')
                // 更新本地存储的token
                setToken(res.token)
                // 执行队列中等待的请求
                failedQueue.forEach((cb) => cb())
                // 清空队列
                failedQueue = []
            } catch (error) {
                console.error('Token刷新失败:', error)
                // 刷新失败时清空队列
                failedQueue = []
            } finally {
                // 无论成功失败，都要重置刷新状态
                isRefreshing = false
            }
        }

        // 将当前请求添加到失败队列，等待token刷新完成后重试
        return new Promise((resolve) => {
            failedQueue.push(() => {
                resolve(http.request(config))
            })
        })
    }

    http.setConfig((defaultConfig) => {
        defaultConfig.baseURL = import.meta.env.VITE_BASE_URL
        return defaultConfig
    })

    http.interceptors.request.use(
        (config) => {
            config.data = config.data || {}
            const defaultCustom = { catch: true, toast: true }
            const defaultHeader = {
                'authorization': `Bearer ${getToken()}`,
                clientid: import.meta.env.VITE_CLIENT_ID,
            }
            config.custom = lodash.merge(defaultCustom, config.custom || {})
            config.header = lodash.merge(defaultHeader, config.header || {})
            return config
        },
        (config) => {
            return Promise.reject(config)
        }
    )

    http.interceptors.response.use(
        (response) => {
            const data = response.data
            const custom = response.config?.custom

            // 可以正常通行的code
            let whiteCodeList = [200]
            let authCodeList = [401]
            if (whiteCodeList.includes(data.code)) {
                return data
            }
            if (authCodeList.includes(data.code)) {
                toast(data.msg)
                if (isGoLogin) {
                    return new Promise(() => { })
                }
                isGoLogin = true
                setTimeout(() => {
                    isGoLogin = false
                    uni.navigateTo({ url: '/pages/login/index' })
                }, 1000)
                return new Promise(() => { })
                // return handleTokenRefresh(response.config)
            }
            if (custom.toast !== false) {
                toast(data.message || data.msg)
            }
            if (custom?.catch) {
                return Promise.reject(data)
            } else {
                return new Promise(() => { })
            }
        },
        (response) => {
            const data = response.data
            if (data.code === 401) {
                toast(data.msg)
                if (isGoLogin) {
                    return new Promise(() => { })
                }
                isGoLogin = true
                setTimeout(() => {
                    isGoLogin = false
                    uni.navigateTo({
                        url: '/pages/login/index'
                    })
                }, 1000)
                return new Promise(() => { })
                // return handleTokenRefresh(response.config)
            }
            return Promise.reject(response)
        }
    )
}
